package com.starry.module.system.core.file.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.io.IoUtil;
import com.starry.core.common.execption.ServiceException;
import com.starry.module.system.api.file.domain.qo.SysFileQo;
import com.starry.module.system.core.file.client.FileClient;
import com.starry.module.system.core.file.client.domain.UploadSuccessDto;
import com.starry.module.system.core.file.client.utils.FileTypeUtils;
import com.starry.module.system.core.file.service.FileConfigService;
import com.starry.module.system.core.file.service.FileService;
import com.starry.module.system.core.file.service.SysFileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件存储
 *
 * @author xiaoke
 */
@Slf4j
@Service
public class FileServiceImpl implements FileService {

    private final FileConfigService fileConfigService;
    private final SysFileService sysFileService;

    public FileServiceImpl(FileConfigService fileConfigService, SysFileService sysFileService) {
        this.fileConfigService = fileConfigService;
        this.sysFileService = sysFileService;
    }

    @Override
    public SysFileQo createFile(MultipartFile file, Boolean isPublic) {
        FileClient masterClient = fileConfigService.getMasterClient();
        UploadSuccessDto uploadSuccess;
        String fileType;
        try {
            fileType = FileTypeUtils.getMineType(IoUtil.readBytes(file.getInputStream()), file.getOriginalFilename());
            uploadSuccess = masterClient.upload(IoUtil.readBytes(file.getInputStream()), file.getOriginalFilename(), fileType);
        } catch (Exception e) {
            log.error("文件上传失败", e);
            throw new ServiceException(e.getMessage());
        }

        SysFileQo sysFileQo = new SysFileQo();

        BeanUtil.copyProperties(uploadSuccess, sysFileQo);

        sysFileQo.setFileType(fileType);
        sysFileQo.setFileSize(file.getSize());
        sysFileQo.setIsPublic(isPublic);

        sysFileQo.setId(sysFileService.save(sysFileQo));

        return sysFileQo;
    }

    @Override
    public byte[] getFileContent(Long configId, String path) throws Exception {
        FileClient client = fileConfigService.getFileClient(configId);
        if (client == null) {
            throw new ServiceException("找不到文件存储配置");
        }
        return client.getContent(path);
    }
}
